import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { In, Not, Repository } from 'typeorm';
import { Notices } from './notices.entity';
import { NoticeIsDeleteEnum, NoticeReadTypeEnum } from './notices.enum';

@Injectable()
export class NoticesService {
  constructor(
    @InjectRepository(Notices)
    private repository: Repository<Notices>,
  ) {}


  async getNotRead(wx_user: string): Promise<number>{
    //查询是否是精简版
    let findLite = await this.repository.query(`
      select count(1) as total from user_setting 
      where user_setting.key = 'clientVersion' and user_setting.value = 'lite' and user_setting.wx_user = ?
    `,[wx_user])
    let liteSql = ``
    if((findLite[0].total || 0) > 0){
      liteSql = `and (
        notices.type = 14 or notices.type = 15 or notices.video_id in (
          select id from video
          where video.original = 1 and video.overseas = 1
        )
      )`
    }

    let total = await this.repository.query(`
      select count(1) as total from notices
      where wx_user = ? and is_read = ? and is_delete = ? and (notices.effect_time is null or notices.effect_time <= now()) ${liteSql}
    `,[wx_user, NoticeReadTypeEnum.not_read, NoticeIsDeleteEnum.no])
    return Number(total?.[0]?.total || 0)
  }

  async findAll_By_WxUser(wx_user: string, take: number, skip: number): Promise<{dataList: Notices[], overseas: any, total: Number}> {
    let findOverseas = await this.repository.query(`select user_setting.value from user_setting where user_setting.key = 'overseas' and user_setting.wx_user = ?`,[wx_user])
    let overseas = 0
    if(findOverseas.length > 0){
      overseas = findOverseas[0].value
    }
    //查询是否是精简版
    let findLite = await this.repository.query(`
      select count(1) as total from user_setting 
      where user_setting.key = 'clientVersion' and user_setting.value = 'lite' and user_setting.wx_user = ?
    `,[wx_user])
    let liteSql = ``
    if((findLite[0].total || 0) > 0){
      liteSql = `and (
        notices.type = 14 or notices.type = 15 or notices.video_id in (
          select id from video
          where video.original = 1 and video.overseas = 1
        )
      )`
    }
    let questionParams = [wx_user, wx_user, wx_user, wx_user, wx_user]
    let list = await this.repository.query(`
      select notices.*, reject_reason.reason, notices.reject_reason,
        (
          select a.id from (
            select video.*, questions.post_answer, questions.create_time as question_time from questions
            left join video on video.id = questions.video_id
            where questions.wx_user = ? and questions.delete_tag = 0
            union
            select video.*, questions.post_answer, video.create_time as question_time from video
            left join questions on questions.video_id = video.id
            where video.wx_user = ? and video.original = 0 and video.isreward = 0 and video.id not in (
              select video_id from questions
              where questions.wx_user = ?
            )
            union
            select video.*, questions.post_answer, video.create_time as question_time from video
            left join questions on questions.video_id = video.id
            inner join reward_success on reward_success.video_id = video.id
            where video.wx_user = ? and video.original = 0 and video.isreward = 1 and video.id not in (
              select video_id from questions
              where questions.wx_user = ?
            )
          ) a
          where a.id = notices.video_id
        ) question_a,
        (
          select count(1) from answer
          inner join video on video.id = answer.video_id
          inner join questions on questions.video_id = video.id
          where answer.id = notices.answer_id and questions.wx_user = notices.wx_user and questions.delete_tag = 0
        ) question_c,
        (
          select count(1) from wx_like_video
          where wx_like_video.video_id = notices.video_id and wx_like_video.wx_user = notices.wx_user
        ) collection,
        (
          SELECT count(1) from answer
          inner join video on video.id = answer.video_id
          where video.wx_user != answer.wx_user and answer.delete_tag = 0 and answer.type = 0 and video.delete_tag = 0
            and (
              (notices.answer_id is null and answer.video_id = notices.video_id) or
              (notices.answer_id is not null and answer.id = notices.answer_id)
            )
        ) answer,
        (
          select count(1) from video
          where video.id = notices.video_id and video.wx_user = notices.wx_user and video.original = 1 and video.overseas = 1 and video.delete_tag = 0 and video.wx_user in (
            select user_setting.wx_user from user_setting where user_setting.key = 'overseas' and user_setting.value = ?
          )
        ) as original,
        (
          select count(1) from video
          where video.id = notices.video_id and video.wx_user = notices.wx_user and video.original = 1 and video.overseas = 3 and video.delete_tag = 0 and video.wx_user in (
            select user_setting.wx_user from user_setting where user_setting.key = 'overseas' and user_setting.value = ?
          )
        ) as original_overseas,
        (
          select count(1) from video
          inner join internet_celebrity_group on internet_celebrity_group.id = video.ic_group
          inner join platform on platform.ic_group = video.ic_group
          where (
            (
              video.overseas = 1 and video.profit_type = 0 and video.original = 1
            )
            or (
              video.overseas = 3 and video.profit_type = 0 and video.original = 1
            )
            or(
              (video.overseas = 0 or video.original = 0) 
              and (
                (
                  internet_celebrity_group.type = 0 and (
                    platform.platform in (select setting.value from setting where setting.key = 'level3')
                    or (select count(1) from platform where platform.platform != '' and platform.ic_group = internet_celebrity_group.id) = 0
                  )
                )
                or internet_celebrity_group.type = 3
              )
              and (
                (video.original = 0 and (video.in_ic = 0 or video.in_ic is null))
                or (video.original = 1 and video.in_ic = 0)
              )
            )
          ) and video.id = notices.video_id
        ) as workSource,
        (
          select count(1) from video
          inner join answer on answer.video_id = video.id
          inner join internet_celebrity_group on internet_celebrity_group.id = video.ic_group
          inner join platform on platform.ic_group = video.ic_group
          where (
            (
              video.overseas = 1 and video.profit_type = 0 and video.original = 1
            )
            or (
              video.overseas = 3 and video.profit_type = 0 and video.original = 1
            )
            or(
              (video.overseas = 0 or video.original = 0) 
              and (
                (
                  internet_celebrity_group.type = 0 and (
                    platform.platform in (select setting.value from setting where setting.key = 'level3')
                    or (select count(1) from platform where platform.platform != '' and platform.ic_group = internet_celebrity_group.id) = 0
                  )
                )
                or internet_celebrity_group.type = 3
              )
              and (
                (video.original = 0 and (video.in_ic = 0 or video.in_ic is null))
                or (video.original = 1 and video.in_ic = 0)
              )
            )
          ) and answer.id = notices.answer_id
        ) as workSource2,
        profit_refund.create_time as consume_time,
        notices.profit_time as profit_time,
        notices.content,
        (
          select count(1) from questions where video_id = notices.video_id and questions.wx_user = notices.wx_user
        ) as video_question,
        (
          select count(1) from video where video_id = notices.video_id and video.original = 1 and video.wx_user = notices.wx_user
        ) as video_original,
        (
          select count(1) from wx_like_video where video_id = notices.video_id and wx_like_video.wx_user = notices.wx_user
        ) as video_collection
      from notices
      left join reject_reason on reject_reason.id = notices.reject_reason
      left join profit_refund on profit_refund.id = notices.profit_refund_id
      where notices.wx_user = ? and (notices.effect_time is null or notices.effect_time <= now())
        ${liteSql}
      order by notices.id desc
      limit ?,?
    `,[...questionParams, overseas, overseas, wx_user, skip, take])

    let total = await this.repository.query(`
      select count(1) as total
      from notices
      where notices.wx_user = ? and (notices.effect_time is null or notices.effect_time <= now())
        ${liteSql}
    `,[wx_user])
    return {dataList:list, overseas: overseas, total: Number(total[0].total || 0)}
  }

  /**
   * 批量阅读通知
   * @param ids
   */
  async readNotices(ids:number[]){
    return await this.repository.update({id:In(ids)},{is_read: NoticeReadTypeEnum.is_read})
  }

  findAll(): Promise<Notices[]> {
    return this.repository.find();
  }

  findOne(id: any): Promise<Notices> {
    return this.repository.findOne(id);
  }

  async remove(id: number): Promise<void> {
    await this.repository.delete(id);
  }

  async create(data: Notices): Promise<Notices> {
    let saveData = new Notices()
    saveData.answer_id = data.answer_id
    saveData.create_time = new Date()
    saveData.type = data.type
    saveData.video_id = data.video_id
    saveData.wx_user = data.wx_user
    return await this.repository.create(saveData)
  }
}
